import { getUserInfo,getUserAccount } from "@/api/user";
import moment from "moment";
const userinfo = localStorage.getItem("userinfo");
const actions = {
  async getUserInfo({ commit,state }, token) {
    let tokenTime = moment().valueOf();
    if (token) {
      localStorage.setItem("token", token);
      localStorage.setItem("tokenTime", tokenTime);
    }else {
        token = localStorage.getItem("token");
        tokenTime = localStorage.getItem("tokenTime");  
    }
    const res = await getUserInfo();
    console.log("userinfo", token);
    commit("SET_USERINFO", { data: res.data, token, tokenTime });
  },

  async getUserAccountInfo({commit},token) {
    let tokenTime = moment().valueOf();
    if (token) {
      localStorage.setItem("token", token);
      localStorage.setItem("tokenTime", tokenTime);
    }else {
        token = localStorage.getItem("token");
        tokenTime = localStorage.getItem("tokenTime");  
    }
    const res = await getUserAccount();
    console.log("userinfo@@@@@@", res);
    commit("SET_USERINFO", { data: res.result, token, tokenTime });
  },

  async logout({ commit }) {
    await localStorage.removeItem("token");
    commit("LOGOUT");
  },
};
const mutations = {
  SET_USERINFO(state, { data, token, tokenTime }) {
    localStorage.setItem("userinfo", JSON.stringify(data));
    state.userInfo = data;
    state.token = token;
    state.tokenTime = tokenTime;
  },
  LOGOUT(state) {
    localStorage.removeItem("userinfo");
    localStorage.removeItem("tokenTime");
    state.userInfo = {};
    state.tokenTime = null;
    state.token = "";
  },
};
const state = () => ({
  tokenTime: localStorage.getItem("tokenTime") || null,
  token: localStorage.getItem("token") || "",
  userInfo: userinfo ? JSON.parse(userinfo) : {},
});

const user = {
  namespaced: true,
  actions,
  mutations,
  state,
};

export default user;
